import { CellEvent, GridApi, GridReadyEvent, ValueFormatterParams, ValueGetterParams } from 'ag-grid-community';
import { formatDateTime } from 'src/utils/dayjs';
import { onMounted, ref } from 'vue';

/**
 * 获得序号
 * @param params ValueGetterParams ag-grid
 */
export const getRowNumber = (params: ValueGetterParams) => (params?.node?.rowIndex ?? 0) + 1;

/**
 * 格式化日期
 * @param params ValueFormatterParams ag-grid
 * @param format? 日期格式， 默认 YYYY-MM-DD HH:mm:ss
 */
export const dateTimeValueFormatter = (params: ValueFormatterParams, format?: string) =>
  formatDateTime(params.value, format);

/**
 * 表格高度自动计算
 * @param idOrTarget 需要扣除高度的 id 或 target, 支持 string 或 string[] 或忽略, 如 yard-order-toolbar, [toolbar, header]
 * @param options 可选选项
 * @param options.method 默认 getElementById, 也可以是 querySelector
 * @param options.fixedOffset 固定扣除的 px 高度, 默认 68 px 即 q-header 高度
 * @param options.pageHeight 页面高度, 默认 100vh
 */
export const useTableHeight = (
  idOrTarget?: string | string[],
  options: { fixedOffset?: number; pageHeight?: string; method?: 'getElementById' | 'querySelector' } = {},
) => {
  const { fixedOffset = 200, pageHeight = '100vh', method = 'getElementById' } = options;

  const tableHeight = ref<string>();

  onMounted(() => {
    let targetHeight = 0;
    if (typeof idOrTarget === 'string') {
      targetHeight = document[method](idOrTarget)?.clientHeight ?? 0;
    } else if (Array.isArray(idOrTarget)) {
      for (const targetItem of idOrTarget) {
        targetHeight += document[method](targetItem)?.clientHeight ?? 0;
      }
    }
    tableHeight.value = `calc(${pageHeight} - ${targetHeight + fixedOffset}px)`;
  });

  return tableHeight;
};

/**
 * 初始化 gridApi, 一般和 @grid-ready 配合
 *
 * @example [gridApi, setGridApi] = useGridApi()
 */
export const useGridApi = <TData = any>() => {
  const gridApi = ref<GridApi<TData>>();
  const setGridApi = (event: GridReadyEvent) => {
    gridApi.value = event.api;
  };
  return [gridApi, setGridApi] as const;
};

/**
 * 获取选中的数据行, 一般和 @cell-context-menu, @selection-changed 配合
 *
 * [selectedRow, setSelectedRow] = useSelectedRow()
 */
export const useSelectedRow = <T = any>() => {
  const selectedRow = ref<T>();
  const setSelectedRow = (event: CellEvent<T>) => {
    selectedRow.value = event.data;
  };
  return [selectedRow, setSelectedRow] as const;
};

/**
 * 生成 ag-grid 右键数据行的 target
 * @param id 可选表格 ID
 * @returns
 */
export const composeMenuTarget = (id?: string) =>
  id ? `#${id} .ag-center-cols-container` : '.ag-center-cols-container';
